/* Copyright 2010 John L. Reilly

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

package com.riq;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.riq.entity.Tracking;

@SuppressWarnings("serial")
public class ResourceServlet extends HttpServlet {
	
  private static final Logger log = Logger.getLogger(Tracking.class.getName());
  private static final Long INIT_LONG = Long.valueOf("999999999");
  
  private String responseType;
  private String intent;
  private String action;
  private Long deptId;
  private Long alertId;
  
  public void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
    doGet(request, response);
  }
  
  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException { 
  
  log.info("INSIDE resourceservlet");
  
  // -----------------------------------------------------------------------------------------------
  //  HEADER
  // -----------------------------------------------------------------------------------------------
  
  Cookie[] cookie = request.getCookies();
  deptId = Long.valueOf(ServletUtilities.getCookieValue(cookie, "cvDeptId", "999999999"));
  alertId = Long.valueOf(ServletUtilities.getCookieValue(cookie, "cvAlertId", "999999999"));
  
  action = request.getParameter("action"); 
  intent = request.getParameter("intent"); 

  // -----------------------------------------------------------------------------------------------
  //  METHOD DIRECTORY
  // -----------------------------------------------------------------------------------------------

    if ("add".equalsIgnoreCase(action)) {
      add(response, request); 
    } else { 
      response.sendRedirect("mainMenu.html"); 
    }
  }
    
  // ---------------------------------------------------------------------------------------------
  //  METHODS
  // ---------------------------------------------------------------------------------------------

  private void add(HttpServletResponse response, ServletRequest request) 
  throws ServletException, IOException {
    
    PersistenceManager pm = PMF.get().getPersistenceManager();
    ArrayList<Long> selectedMembers = new ArrayList<Long>();
    ArrayList<Long> selectedLocations = new ArrayList<Long>();
    
    response.setContentType("text/html");  // TODO ????
    Enumeration<?> paramNames = request.getParameterNames();
    request.setAttribute("paramNames", paramNames);
    
    Long deptId = null;
    Long alertId = null;
    Long memberId = null;
    Long locationId = null;

    while(paramNames.hasMoreElements()) {

      String paramName = (String)paramNames.nextElement();
      System.out.println("paramName: " + paramName);

      String[] paramValues = request.getParameterValues(paramName);

      if (paramValues.length >= 1) {
        
        String paramValue = paramValues[0];
        System.out.println("paramValue: " + paramValue);
        
        // only one department owns alert
        // mutual aid resources can be assigned (through memberId paramName below)
        if (paramName.matches("deptId")) {
          deptId = Long.valueOf(paramValue);
          System.out.println("deptId: " + deptId);
          
        // only one alert
        } else if (paramName.matches("alertId") ) {
          alertId = Long.valueOf(paramValue);
          System.out.println("alertId: " + alertId);
          
        // multiple locations allowed
        } else if (paramName.matches("locationId") ) {
          for (int i=0; i < paramValues.length; i++) {  
            locationId = Long.valueOf(paramValues[i]);
            System.out.println("locationId: " + locationId);
            selectedLocations.add(locationId);  
          }
          
        // multiple members allowed
        } else if (paramName.matches("memberId")) {
          for (int i=0; i < paramValues.length; i++) {  
            memberId = Long.valueOf(paramValues[i]);
            System.out.println("memberId: " + memberId);
            selectedMembers.add(memberId);  
          }
        } 
        
      }
    }
        
    for (int j=0; j < selectedMembers.size(); j++) {
      Tracking t1 = new Tracking (
        deptId,
        alertId,
        null,
        System.currentTimeMillis(),
        null, 
        "member",
        selectedMembers.get(j),
        null,
        "manuallyAddMember"
        );
      pm.makePersistent(t1);
    }
  
    for (int k=0; k < selectedLocations.size(); k++) {
      Tracking t2 = new Tracking (
        deptId,
        alertId,
        selectedLocations.get(k),
        System.currentTimeMillis(),
        null, 
        "locstat",
        selectedLocations.get(k),
        null,
        "manuallyAddLocation"
        );
        pm.makePersistent(t2);
    }
        
    RequestDispatcher dispatcher = 
      getServletContext().getRequestDispatcher("/reportingPrep?&alertId=" + alertId + 
    	  "&intent=" + intent);
        dispatcher.forward(request, response);
    
  }

}




